package com.amir.common.utils

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import java.util.regex.Pattern

object AppVersionUtils {
    /**
     * 获取当前app version code
     */
    fun getAppVersionCode(context: Context): Long {
        var appVersionCode: Long = 0
        try {
            val packageInfo: PackageInfo = context.applicationContext
                .packageManager
                .getPackageInfo(context.packageName, 0)
            appVersionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                packageInfo.versionCode.toLong()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            LogUtils.E("${e.message}")
        }
        return appVersionCode
    }


    /**
     * 获取当前app version name
     */
    fun getAppVersionName(context: Context): String? {
        var appVersionName = ""
        try {
            val packageInfo = context.applicationContext
                .packageManager
                .getPackageInfo(context.packageName, 0)
            appVersionName = packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            LogUtils.E("${e.message}")
        }
        return appVersionName
    }

    fun compareVersion(v1: String, v2: String): Boolean? {
        if (v1 == null || v1.length < 1 || v2 == null || v2.length < 1) return null
        val regEx = "[^0-9]"
        val p = Pattern.compile(regEx)
        var s1: String = p.matcher(v1).replaceAll("").trim()
        var s2: String = p.matcher(v2).replaceAll("").trim()

        val cha: Int = s1.length - s2.length
        var buffer = StringBuffer()
        var i = 0
        while (i < Math.abs(cha)) {
            buffer.append("0")
            ++i
        }

        if (cha > 0) {
            buffer.insert(0,s2)
            s2 = buffer.toString()
        } else if (cha < 0) {
            buffer.insert(0,s1)
            s1 = buffer.toString()
        }

        val s1Int = s1.toInt()
        val s2Int = s2.toInt()

        return s1Int > s2Int
    }
}